<?php
namespace app\web\controller;

use app\model\Util; 
use app\model\Theme; 
use app\model\Bargain as Bargain_mod;

class Bargain extends Base
{
    public function Bargain()
    {
/**
 * Created by 底片云
 * Desc:抽奖机会
 * User:cbw
 * Date: 2020/11/29
 */

global $_G,$_P;
$params = $_P;
$themeid = isset($params['themeid'])?$params['themeid']:'';//活动id
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
if (!$theme){
    $response = modelShow(40002);
    return_msg($response, '', 'ajax');
}
$config =   Theme::getConfig($themeid);
$themelist = Theme::getAllTheme();
$system= $_G['system'];
$do = 'bargain';
$ac = !empty($params['ac'])?$params['ac']:'display';
$nickname = isset($params['nickname'])?trim($params['nickname']):'';

    if (empty($_P['createtime']['start'])){
        $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
        $start_day =  strtotime(date('Y-m-d 00:00:00',$start_day));
    }else{
        $start_day =  strtotime($_P['createtime']['start']);
    }
    $end_day = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;

// $start_day = isset($params['createtime']['start'])?$params['createtime']['start']:time();
// $end_day = isset($params['createtime']['end'])?$params['createtime']['end']:time();
$order_id = isset($params['order_id'])?$params['order_id']:'';
$search_data = isset($params['search_data'])?$params['search_data']:'';
$current_status  = isset($params['status'])?$params['status']:0;
$be_id  = isset($params['be_id'])?$params['be_id']:0;
$page_index = max(1,intval($params['page']));
$page_size = 50;
$page_start = ($page_index-1)*$page_size;
$lt_item_page_total = intval(db_find("select count(*) as cnt from".tablename(t_bargain_entry))['cnt']);
$type_options = Bargain_mod::getBargainStatusList($themeid);
if ($ac=='display'){
    $listarr = Bargain_mod::getDefaultOrSearchBargainEntry($themeid,$nickname,'','','',$current_status,$page_start,$page_size);
    $list = $listarr['list'];
    $page_total = $listarr['total'];
    $pager = pagination($page_total,$page_index,$page_size);
    $total = count($list);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=='search'){
    if (is_int($order_id)){
        $nickname = '';
    }elseif (is_string($order_id)){
        $nickname =$order_id;
        $order_id = '';
    }
    if (!empty($nickname)){
        $nickname = '%'.$nickname.'%';
    }
    // if ($start_day==$end_day){
    //     $listarr = Bargain_mod::getDefaultOrSearchBargainEntry($themeid,$nickname,'','',$order_id,$current_status,$page_start,$page_size);
    // }else{
        $listarr = Bargain_mod::getDefaultOrSearchBargainEntry($themeid,$nickname,$start_day,$end_day,$order_id,$current_status,$page_start,$page_size);
    // }
    if(checksubmit('export_submit', true)){
        $count = $listarr['total'];
        $page_limit = 2000;
        $pagesize = ceil($count/$page_limit);
        $header = array(
            'nickname' => '微信昵称',
            'username' => '用户姓名',
            'mobile' => '用户联系方式',
            'remain_amount' => '当前砍至金额',
            'status' => '状态',
            'pay_status' => '支付状态',
            'created_at' => '创建时间',
            'end_time' => '结束时间',
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
        for ($j = 1; $j <= $pagesize; $j++) {

            $first_condition = " where a.themeid=$themeid";
            if ($current_status!=0){
                $first_condition = " where a.themeid=$themeid and a.status=$current_status";
            }
            $ex_page = $_P['ex_page']?$_P['ex_page']:1;
            $page_start = ($ex_page-1)*$page_limit;
            $last_condition = " order by  a.created_at desc limit ".$page_start.",".$page_limit;
            $condition = "";
            if ($nickname){
                $condition .= "  and b.nickname like '".$nickname."' ";
            }
            if ($start_day && $end_day){
                $condition .= "  and a.created_at between '".date("Y-m-d H:i:s",$start_day)."' and '".date("Y-m-d H:i:s",$end_day)."' ";
            }
            if ($order_id){
                $condition .= "  and a.order_id='".$order_id."' ";
            }
            $sql = "select a.*,b.username,b.avatar,b.nickname,b.mobile  from ".tablename(t_bargain_entry).
                " as a  LEFT JOIN ". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid ".$first_condition.$condition.$last_condition;
            $list = db_select($sql);
            foreach ($list as $key => $val){
                if (!$val['order_id']){
                    $list[$key]['pay_status'] = 0;
                }else{
                    $order_item = db_get(t_record,['themeid'=>$themeid,'id'=>$val['order_id']]);
                    if (!$order_item){
                        $list[$key]['pay_status'] = 0;
                    }else{
                        if ($order_item['status']==1){
                            $list[$key]['pay_status'] = 1;
                        }else{
                            $list[$key]['pay_status'] = 0;
                        }
                    }
                }
            }

            if (!empty($list)) {

                foreach ($list as $row) {
                    $row['nickname']=str_replace('"',"",$row['nickname']);
                    $row['nickname']=str_replace(',',"",$row['nickname']);
                        switch ($row['status']){
                            case 1:
                                $row['status'] = '完成';
                                break;
                            case 2:
                                $row['status'] = '未完成';
                                break;
                            case 3:
                                $row['status'] = '已过期';
                                break;
                            default:
                                $row['status'] ='异常';
                                break;
                        }
                    switch ($row['pay_status']){
                        case 0:
                            $row['pay_status'] = '未支付';
                            break;
                        case 1:
                            $row['pay_status'] = '已支付';
                            break;
                        default:
                            $row['pay_status'] = '未支付';
                            break;
                    }
                    foreach ($keys as $key) {
                        $data[] = $row[$key];
                    }
                    $user[] = implode("\t ,", $data) . "\t ,";
                    unset($data);
                }
                $html .= implode("\n", $user);

            }
        }
        //新版本导出合并
        $is_end = 0;
        if($ex_page>=$pagesize){
            $is_end = 1;
        }
        Util::WxJump($system,$html,'砍价列表',$themeid,$is_end,$pagesize);
    }
    $list = $listarr['list'];
    $page_total = $listarr['total'];
    $pager = pagination($page_total,$page_index,$page_size);
    $total = count($list);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=='detail'){
//    $page_total = intval(db_find("select count(*) as cnt from ".tablename(t_bargain_flag)." where be_id=".$be_id)['cnt']);
    $lists = Bargain_mod::getBargainFlagList($themeid,$be_id,0,0);
    $list = Bargain_mod::getBargainFlagList($themeid,$be_id,$page_start,$page_size);
    $page_total = count($lists);
    $pager = pagination($page_total,$page_index,$page_size);
    $total = count($list);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=='detail_search'){
    $search_data = '%'.$search_data.'%';
    if (empty($_P['createtime']['start'])){
        $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
        $start_day =  date('Y-m-d',$start_day);
    }else{
        $start_day =  $_P['createtime']['start'];
    }
    $end_day = empty($_P['createtime']['end']) ? date('Y-m-d',TIMESTAMP): $_P['createtime']['end'] ;

    $lists = Bargain_mod::getBargainHelpFlagList($themeid,$search_data,$start_day,$end_day,0,0);
    $total = count($lists);

    if(checksubmit('export_submit', true)){
        $count = $total;
        $page_limit = 2000;
        $pagesize = ceil($count/$page_limit);
        $header = array(
            'entry_username' => '发起人姓名','entry_nickname' => '发起人昵称', 'entry_mobile' => '发起人联系方式', 'username' => '帮砍人姓名','nickname' => '帮砍人昵称',
            'mobile' => '帮砍人手机号','sub_amount' => '帮砍金额',
            'created_at'=>'创建时间'
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
        //for ($j = 1; $j <= $pagesize; $j++) {

            $condition = " where a.themeid=$themeid ";
            if ($search_data){
                $condition .= " and c.username like '".$search_data."'"." or c.mobile like '".$search_data."' ";
            }
            if ($start_day && $end_day){
                $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
            }

//            $sql = "select a.*,b.username,b.nickname,b.mobile,c.avatar as entry_avatar,c.username as entry_username,c.nickname as entry_nickname,c.mobile as entry_mobile from ".
//                tablename(t_bargain_flag)." as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
//                " LEFT JOIN". tablename(t_fans)." as c on a.from_uid=c.uid and a.themeid=c.themeid".$condition.
//                " group by a.from_uid order by a.created_at desc limit ". ($j - 1) * 5000 . ",5000 ";
           $ex_page = $_P['ex_page']?$_P['ex_page']:1;
            $sql = "select a.*,b.username,b.nickname,b.mobile,c.avatar as entry_avatar,c.username as entry_username,c.nickname as entry_nickname,c.mobile as entry_mobile from ".
                tablename(t_bargain_flag)." as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
                " LEFT JOIN". tablename(t_fans)." as c on a.from_uid=c.uid and a.themeid=c.themeid".$condition.
                "  order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";
            $list = db_select($sql);

            if (!empty($list)) {

                foreach ($list as $row) {
                    $row['entry_nickname']=str_replace('"',"",$row['entry_nickname']);
                    $row['entry_nickname']=str_replace(',',"",$row['entry_nickname']);

                    $row['nickname']=str_replace('"',"",$row['nickname']);
                    $row['nickname']=str_replace(',',"",$row['nickname']);
//                        switch ($row['status']){
//                            case 0:
//                                $row['status'] = '未填写信息';
//                                break;
//                            case 1:
//                                $row['status'] = '已填写信息';
//                                break;
//                            case 2:
//                                $row['status'] = '已核销';
//                                break;
//                            default:
//                                break;
//                        }
//                        unset($info);
                    foreach ($keys as $key) {
                        $data[] = $row[$key];
                    }
                    $user[] = implode("\t ,", $data) . "\t ,";
                    unset($data);
                }
                $html .= implode("\n", $user);

           // }
        }
        //新版本导出合并
        $is_end = 0;
        if($ex_page>=$pagesize){
            $is_end = 1;
        }
        Util::WxJump($system,$html,'帮砍有礼-粉丝礼品信息',$themeid,$is_end,$pagesize);
    }
    $list = Bargain_mod::getBargainHelpFlagList($themeid,$search_data,$start_day,$end_day,$page_start,$page_size);
    $page_total = $total;
    $pager = pagination($page_total,$page_index,$page_size,$pagesize);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=='del'){
    $res = Bargain_mod::delBargainEntryByBeid($themeid,$be_id);
    $total = count($list);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=='help_gift'){
    $state = isset($_P['state'])?$_P['state']:2;
    $all_type_num = count(Bargain_mod::getHelpReceiveList(['themeid'=>$themeid]));
    $not_type_num = count(Bargain_mod::getHelpReceiveList(['themeid'=>$themeid,'status'=>0]));
    $has_type_num = count(Bargain_mod::getHelpReceiveList(['themeid'=>$themeid,'status'=>1]));

    $other_name = $config['bargain_help_gift_other_name'];
    $other_phone = $config['bargain_help_gift_other_phone'];
    $lists = Bargain_mod::getHelpReceiveFlag($themeid,'','','',0,0);
    $list = Bargain_mod::getHelpReceiveFlag($themeid,'','','',$page_start,$page_size,$state);
    $total = count($lists);
    $page_total = $total;
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=="help_gift_search"){

    $state = isset($_P['state'])?$_P['state']:2;

    $all_type_num = count(Bargain_mod::getHelpReceiveList(['themeid'=>$themeid]));
    $not_type_num = count(Bargain_mod::getHelpReceiveList(['themeid'=>$themeid,'status'=>0]));
    $has_type_num = count(Bargain_mod::getHelpReceiveList(['themeid'=>$themeid,'status'=>1]));

    $search_data = '%'.$search_data.'%';
    $other_name = $config['bargain_help_gift_other_name'];
    $other_phone = $config['bargain_help_gift_other_phone'];



    $lists = Bargain_mod::getHelpReceiveFlag($themeid,$search_data,$start_day,$end_day,0,0);
    $total = count($lists);
    if(checksubmit('export_submit', true)){
        $count = $total;
        $page_limit = 2000;
        $pagesize = ceil($count/$page_limit);
        $header = array(
            'uid' => '会员UID', 'user_name' => '姓名', 'user_mobile' => '手机',
            'nickname' => '微信昵称','g_name' => '礼品名称',  'status' => '状态',
            'created_at'=>'创建时间'
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
//        for ($j = 1; $j <= $pagesize; $j++) {

            $condition = " where a.themeid=$themeid ";
            if ($state!=2){
                $condition .= " and a.status=".$state;
            }
            if ($search_data){
                $condition .= " and a.user_name like '".$search_data."'"." or a.user_mobile like '".$search_data."' ";
            }
            if ($start_day && $end_day){
                $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
            }
            $ex_page = $_P['ex_page']?$_P['ex_page']:1;
            $sql = "select a.*,b.avatar,b.nickname from ".tablename(t_bargain_help_gift).
                " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".$condition.
                " group by a.uid order by a.uid desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";
            $list = db_select($sql);

            if (!empty($list)) {
                $size = ceil(count($list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($list, $i * 500, 500);
                    foreach ($buffer as $row) {
                        switch ($row['status']){
                            case 0:
                                $row['status'] = '未填写信息';
                                break;
                            case 1:
                                $row['status'] = '已填写信息';
                                break;
                            case 2:
                                $row['status'] = '已核销';
                                break;
                            default:
                                break;
                        }
                        unset($info);
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        $user[] = implode("\t ,", $data) . "\t ,";
                        unset($data);
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
           // }
        }
        //新版本导出合并
        $is_end = 0;
        if($ex_page>=$pagesize){
            $is_end = 1;
        }
        Util::WxJump($system,$html,'帮砍有礼-粉丝礼品信息',$themeid,$is_end,$pagesize);
    }
    $list = Bargain_mod::getHelpReceiveFlag($themeid,$search_data,$start_day,$end_day,$page_start,$page_size,$state);

    $page_total = $total;
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/bargain', $return_clicent);
}
if ($ac=='convert_help_gift'){
    //核销礼品
    $hg_id = $_P['hg_id'];
    $where = ['hg_id'=>$hg_id];
    $data = ['status'=>1];
    $res = Bargain_mod::editHelpReceiveFlagItem($where,$data);
    if (!$res){
        $response = modelShow(30000);
    }else{
        $response = modelShow(200);
    }
    return_msg($response, '', 'ajax');
}
}
}